package com.smart.thrift.model.wrapper;


import com.smart.thrift.model.common.ThriftServiceSignature;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;

public final class ThriftServiceWrapperFactory {

    public static ThriftServiceWrapper wrapper(String serviceName, Class<?> serviceClass, Object thriftService, double version) {
        ThriftServiceWrapper thriftServiceWrapper;

        Class<?> thriftServiceIface = Arrays.stream(thriftService.getClass().getInterfaces())
                .filter(iface -> iface.getName().endsWith("$Iface"))
                .filter(iface -> iface.getDeclaringClass() != null)
                .findFirst().orElse(null);

        if (version <= -1) {
            thriftServiceWrapper = new ThriftServiceWrapper(serviceName, thriftServiceIface, thriftService);
        } else {
            thriftServiceWrapper = new ThriftServiceWrapper(serviceName, thriftServiceIface, thriftService, version);
        }
        boolean match = Arrays.stream(serviceClass.getInterfaces()).anyMatch(iface -> iface.getName().endsWith("$Iface") && iface.getDeclaringClass() != null);

        ThriftServiceSignature thriftServiceSignature = ThriftServiceSignature.builder()
                .serviceName(serviceName)
                .targetServiceClass(serviceClass)
                .thriftServiceClasses(match ? Collections.singletonList(thriftServiceIface.getDeclaringClass()) : Arrays.asList(serviceClass.getInterfaces()))
                .version(version).build();
        thriftServiceWrapper.setThriftServiceSignature(thriftServiceSignature);

        return thriftServiceWrapper;
    }

    public static Object getTarget(Object obj) {
        if (!AopUtils.isAopProxy(obj)) {
            return obj;
        }
        try {

            //判断是jdk还是cglib代理
            if (AopUtils.isJdkDynamicProxy(obj)) {
                obj = getJdkDynamicProxyTargetObject(obj);
            } else {
                obj = getCglibDynamicProxyTargetObject(obj);
            }

        } catch (Exception e) {

        }
        return obj;

    }

    private static Object getCglibDynamicProxyTargetObject(Object obj) throws Exception {
        Field h = obj.getClass().getDeclaredField("CGLIB$CALLBACK_0");
        h.setAccessible(true);

        Object dynamicAdvisedInterceptor = h.get(obj);
        Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
        advised.setAccessible(true);
        Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
        return target;
    }

    private static Object getJdkDynamicProxyTargetObject(Object obj) throws Exception {

        Field h = obj.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);

        AopProxy aopProxy = (AopProxy) h.get(obj);
        Field advised = aopProxy.getClass().getDeclaredField("advised");
        advised.setAccessible(true);
        Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
        return target;

    }
}
